<script lang="ts">
  import { onDestroy, onMount } from "svelte";
  import * as echarts from "echarts";
  import Title from "../../../components/Title/Title.svelte";
  import { catalog } from "../stores";

  const colors = [
    "#5470c6",
    "#91cc75",
    "#fac858",
    "#ee6666",
    "#73c0de",
    "#3ba272",
    "#fc8452",
    "#9a60b4",
    "#ea7ccc",
  ];
  let myChart;
  let myChart2;
  let unsubscribe;
  let seriesData;
  onMount(() => {
    myChart = echarts.init(document.getElementById("right-middle-pie"));
    myChart2 = echarts.init(document.getElementById("right-middle-bar"));

    unsubscribe = catalog.subscribe(({ data }) => {
      if (Array.isArray(data)) {
        seriesData = data;
        myChart.setOption(getOption(data));
        myChart2.setOption(getOption2(data));
      }
    });
  });

  onDestroy(unsubscribe);

  function getOption(data) {
    data = data.reverse();
    let rate = 1;
    if (window.innerWidth) {
      rate = Math.ceil(window.innerWidth / 1920);
    }
    return {
      title: { text: "", left: "center", top: "center" },
      tooltip: { trigger: "item" },
      animationDuration: 2000,
      series: [
        {
          type: "pie",
          data: data,
          radius: ["50%", "80%"],
          label: {
            color: "rgba(255,255,255,0.8)",
            position: "inside",
            fontSize: 12 * rate,
          },
          itemStyle: {
            borderRadius: 8,
            borderColor: "transparent",
            borderWidth: 2,
            color: (params) => colors[params.dataIndex],
          },
        },
      ],
    };
  }

  function getOption2(data) {
    let rate = 1;
    if (window.innerWidth) {
      rate = Math.ceil(window.innerWidth / 1920);
    }
    return {
      tooltip: { trigger: "item" },
      animationDuration: 2000,
      grid: { top: "10%", bottom: "6%", containLabel: true },
      xAxis: {
        show: false,
        type: "value",
        boundaryGap: [0, 0.01],
      },
      yAxis: {
        type: "category",
        axisLine: false,
        axisTick: false,
        axisLabel: { color: "#fff", fontSize: 12 * rate },
        data: data.map((d) => d.name),
      },
      series: [
        {
          name: "",
          type: "bar",
          barWidth: "30%",
          itemStyle: {
            borderRadius: 10 * rate,
            color: (params) => colors[params.dataIndex],
          },
          data: data.map((d) => d.value),
        },
      ],
    };
  }

  function onResize() {
    myChart.resize();
    myChart2.resize();
  }
</script>

<svelte:window on:resize={onResize} />
<div class="h-full flex flex-col">
  <Title title="设备种类分布" />
  <div class="flex-1 flex h-full">
    <div class="basis-1/2" id="right-middle-pie" />
    <div class="basis-1/2" id="right-middle-bar" />
  </div>
</div>

<style>
</style>
